<?php

class LoginHandler {

	private $userHandler = null;
	private $LoggedIn = "TheActionIsGo";
	private $UserIsAdmin = "GoGoGodzilla";

	public function __construct(UserHandler $userHandler) {
		$this -> userHandler = $userHandler;
	}

	/**
	 * Public function to check if user are logged in or not
	 * @access public
	 * @param -
	 * @return boolean
	 */
	public function isUserLoggedIn() {
		//Check if username has logged in
		if (isset($_SESSION[$this -> LoggedIn]) === true) {
			//its true, return it!
			return TRUE;
		}
		//else return false
		return FALSE;
	}

	/**
	 * Reads session and converts array into user object
	 * @access Public
	 * @param -
	 * @return UserObject
	 */
	public function getLoggedInUser() {
		//Check if username has logged in
		if (isset($_SESSION[$this -> LoggedIn]) === true) {
			//its true, return it!
			return User::convertFromArrayToUser($_SESSION[$this -> LoggedIn]);
		}
		//else return false
		return FALSE;
	}

	/**
	 * Checks if valid user credentials then converts the user to an array and stores it in session
	 * @access public
	 * @param User object
	 * @return userObject OR False
	 */
	public function logIn(User $user) {
		//check if credentials are correct
		$user = $this -> checkCredentials($user);
		//If were good, log in user
		if ($user !== false) {
			//Convert to an array and store in session
			$userAsArray = (array)$user;
			$_SESSION[$this -> LoggedIn] = $userAsArray;
			return $user;
		}
		// Else return false
		else {
			return null;
		}
	}

	/**
	 * Private function to check if credentials match
	 * @access private
	 * @param User object
	 * @return User Object or False if not ok
	 */
	private function checkCredentials(User $user) {
		//Try to fetch user/users from Usertabel
		$compareUser = $this -> userHandler -> getUserByUserName($user -> UserName);
		//Make sure we get a User object in return
		if ($compareUser !== null) {
			//If we were served a crypted password
			if ($compareUser -> PassWord === $user -> PassWord) {
				return $compareUser;
			}
			//If we were served an uncrypted password
			elseif (crypt($user -> PassWord, $compareUser -> Salt) === $compareUser -> PassWord) {
				$user -> PassWord = crypt($user -> PassWord, $compareUser -> Salt);
				return $compareUser;
			}
		}
		return false;
	}

	/**
	 * Public Function to LOGOUT user
	 * @access private
	 * @param -
	 * @return Bool
	 */
	public function logOut() {
		if (isset($_SESSION[$this -> LoggedIn])) {
			unset($_SESSION[$this -> LoggedIn]);
			//setcookie(session_name(), $_COOKIE[session_name()], time() - 10000);
			return true;
		}
		return false;
	}

}
